Page({
    data: {
      activeTab: 'hospital', // 默认显示“医院数据”
      hospitalData: {},
      personalData: {},
      trendData: [],
      deptDistribution: [],
      keyPatients: [],
      timeTrendData: []
    },
  
    onLoad() {
      this.loadMockData();
    },
  
    onReady() {
      // 初始绘制默认Tab的图表
      this.drawCurrentTabChart();
    },
  
    // Tab切换事件
    onTabChange(e) {
      const tab = e.currentTarget.dataset.tab;
      this.setData({ activeTab: tab }, () => {
        this.drawCurrentTabChart(); // 切换后重新绘制对应图表
      });
    },
  
    // 绘制当前Tab对应的图表
    drawCurrentTabChart() {
      if (this.data.activeTab === 'hospital') {
        this.drawPieChart();
      } else if (this.data.activeTab === 'personal') {
        this.drawTimeTrendChart();
      }
    },
  
    // 加载模拟数据（封装为函数，后续替换接口）
    loadMockData() {
      this.setData({
        hospitalData: this.getHospitalMockData(),
        personalData: this.getPersonalMockData(),
        trendData: this.getDailyTrendMockData(),
        deptDistribution: this.getDeptDistributionMockData(),
        keyPatients: this.getKeyPatientsMockData(),
        timeTrendData: this.getTimeTrendMockData()
      });
    },
  
    // 医院数据Mock
    getHospitalMockData() {
      return {
        totalVisit: "218",
        deptRatio: "62%",
        satisfaction: "95%"
      };
    },
  
    // 个人数据Mock
    getPersonalMockData() {
      return {
        myVisit: "86",
        myDeptRatio: "78%",
        mySatisfaction: "98%",
        averageTime: "15min"
      };
    },
  
    // 每日趋势数据Mock
    getDailyTrendMockData() {
      return [
        { day: "18", hospital: 12, personal: 5 },
        { day: "19", hospital: 18, personal: 8 },
        { day: "20", hospital: 15, personal: 6 },
        { day: "21", hospital: 22, personal: 10 },
        { day: "22", hospital: 16, personal: 7 },
        { day: "23", hospital: 20, personal: 9 },
        { day: "24", hospital: 25, personal: 12 }
      ];
    },
  
    // 科室分布数据Mock
    getDeptDistributionMockData() {
      return [
        { dept: "正畸科", ratio: "62%", color: "#2db7f5" },
        { dept: "修复科", ratio: "20%", color: "#4cae4c" },
        { dept: "牙周科", ratio: "12%", color: "#ff9800" },
        { dept: "其他", ratio: "6%", color: "#9c27b0" }
      ];
    },
  
    // 重点患者数据Mock
    getKeyPatientsMockData() {
      return [
        { id: 1, name: "张XX", tag: "待复诊", tagType: "recheck", date: "2025-11-28" },
        { id: 2, name: "李XX", tag: "待随访", tagType: "follow", date: "2025-11-29" },
        { id: 3, name: "王XX", tag: "待复诊", tagType: "recheck", date: "2025-11-30" }
      ];
    },
  
    // 接诊时长数据Mock
    getTimeTrendMockData() {
      return [
        { day: "18", time: 12 },
        { day: "19", time: 15 },
        { day: "20", time: 18 },
        { day: "21", time: 14 },
        { day: "22", time: 16 },
        { day: "23", time: 13 },
        { day: "24", time: 15 }
      ];
    },
  
    // 绘制科室分布饼图
    drawPieChart() {
      const query = wx.createSelectorQuery().in(this);
      query.select('#deptPieChart')
        .fields({ node: true, size: true })
        .exec((res) => {
          if (!res || !res[0]) return;
  
          const canvas = res[0].node;
          const ctx = canvas.getContext('2d');
          const dpr = wx.getSystemInfoSync().pixelRatio;
          canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          ctx.scale(dpr, dpr);
  
          const data = this.data.deptDistribution;
          let startAngle = 0;
          const total = data.reduce((sum, item) => sum + Number(item.ratio.replace('%', '')), 0);
          const centerX = res[0].width / 2;
          const centerY = res[0].height / 2;
          const radius = Math.min(centerX, centerY) - 10;
  
          // 绘制扇形
          data.forEach((item) => {
            const value = Number(item.ratio.replace('%', ''));
            const endAngle = startAngle + (value / total) * 2 * Math.PI;
            
            // 绘制扇形
            ctx.beginPath();
            ctx.moveTo(centerX, centerY);
            ctx.arc(centerX, centerY, radius, startAngle, endAngle);
            ctx.fillStyle = item.color;
            ctx.fill();
            
            // 添加扇形边框
            ctx.strokeStyle = '#fff';
            ctx.lineWidth = 2;
            ctx.stroke();
            
            startAngle = endAngle;
          });
  
          // 绘制中心白色圆
          ctx.beginPath();
          ctx.arc(centerX, centerY, radius * 0.4, 0, 2 * Math.PI);
          ctx.fillStyle = '#fff';
          ctx.fill();
          ctx.strokeStyle = '#f0f2f5';
          ctx.lineWidth = 1;
          ctx.stroke();
  
          // 绘制中心文字
          ctx.fillStyle = '#333';
          ctx.font = 'bold 24px sans-serif';
          ctx.textAlign = 'center';
          ctx.textBaseline = 'middle';
          ctx.fillText('科室分布', centerX, centerY);
        });
    },
  
    // 绘制接诊时长折线图
    drawTimeTrendChart() {
      const query = wx.createSelectorQuery().in(this);
      query.select('#timeTrendChart')
        .fields({ node: true, size: true })
        .exec((res) => {
          if (!res || !res[0]) return;
  
          const canvas = res[0].node;
          const ctx = canvas.getContext('2d');
          const dpr = wx.getSystemInfoSync().pixelRatio;
          canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          ctx.scale(dpr, dpr);
  
          const data = this.data.timeTrendData;
          const chartWidth = res[0].width;
          const chartHeight = res[0].height;
          const padding = { top: 30, right: 20, bottom: 40, left: 50 };
          const pointWidth = (chartWidth - padding.left - padding.right) / (data.length - 1);
          const maxTime = Math.max(...data.map(item => item.time)) + 5;
  
          // 绘制背景网格
          ctx.strokeStyle = '#f0f2f5';
          ctx.lineWidth = 1;
          
          // 绘制水平网格线
          for (let i = 0; i <= maxTime; i += 5) {
            const y = chartHeight - padding.bottom - (i / maxTime) * (chartHeight - padding.top - padding.bottom);
            ctx.beginPath();
            ctx.setLineDash([2, 2]);
            ctx.moveTo(padding.left, y);
            ctx.lineTo(chartWidth - padding.right, y);
            ctx.stroke();
          }
          
          // 绘制垂直网格线
          data.forEach((item, index) => {
            const x = padding.left + index * pointWidth;
            ctx.beginPath();
            ctx.setLineDash([2, 2]);
            ctx.moveTo(x, padding.top);
            ctx.lineTo(x, chartHeight - padding.bottom);
            ctx.stroke();
          });
          ctx.setLineDash([]);
  
          // 1. 绘制坐标轴
          ctx.beginPath();
          ctx.moveTo(padding.left, padding.top);
          ctx.lineTo(padding.left, chartHeight - padding.bottom);
          ctx.lineTo(chartWidth - padding.right, chartHeight - padding.bottom);
          ctx.strokeStyle = '#e0e0e0';
          ctx.lineWidth = 1;
          ctx.stroke();
  
          // 2. 绘制Y轴刻度
          ctx.font = '14px sans-serif';
          ctx.fillStyle = '#666';
          ctx.textAlign = 'right';
          ctx.textBaseline = 'middle';
          
          for (let i = 0; i <= maxTime; i += 5) {
            const y = chartHeight - padding.bottom - (i / maxTime) * (chartHeight - padding.top - padding.bottom);
            
            // 绘制刻度线
            ctx.beginPath();
            ctx.moveTo(padding.left - 5, y);
            ctx.lineTo(padding.left, y);
            ctx.stroke();
            
            // 绘制刻度值
            ctx.fillText(`${i}min`, padding.left - 10, y);
          }
  
          // 3. 绘制X轴日期
          ctx.textAlign = 'center';
          ctx.textBaseline = 'top';
          
          data.forEach((item, index) => {
            const x = padding.left + index * pointWidth;
            ctx.fillText(`${item.day}日`, x, chartHeight - padding.bottom + 10);
          });
  
          // 4. 绘制折线区域填充
          ctx.beginPath();
          ctx.moveTo(padding.left, chartHeight - padding.bottom);
          
          data.forEach((item, index) => {
            const x = padding.left + index * pointWidth;
            const y = chartHeight - padding.bottom - (item.time / maxTime) * (chartHeight - padding.top - padding.bottom);
            
            if (index === 0) {
              ctx.moveTo(x, y);
            } else {
              ctx.lineTo(x, y);
            }
          });
          
          ctx.lineTo(padding.left + (data.length - 1) * pointWidth, chartHeight - padding.bottom);
          ctx.closePath();
          ctx.fillStyle = 'rgba(244, 67, 54, 0.1)';
          ctx.fill();
  
          // 5. 绘制折线
          ctx.beginPath();
          ctx.strokeStyle = '#f44336';
          ctx.lineWidth = 3;
          ctx.lineCap = 'round';
          ctx.lineJoin = 'round';
          
          data.forEach((item, index) => {
            const x = padding.left + index * pointWidth;
            const y = chartHeight - padding.bottom - (item.time / maxTime) * (chartHeight - padding.top - padding.bottom);
            
            if (index === 0) {
              ctx.moveTo(x, y);
            } else {
              ctx.lineTo(x, y);
            }
          });
          
          ctx.stroke();
  
          // 6. 绘制数据点
          data.forEach((item, index) => {
            const x = padding.left + index * pointWidth;
            const y = chartHeight - padding.bottom - (item.time / maxTime) * (chartHeight - padding.top - padding.bottom);
            
            // 绘制外圈
            ctx.beginPath();
            ctx.arc(x, y, 8, 0, 2 * Math.PI);
            ctx.fillStyle = '#fff';
            ctx.strokeStyle = '#f44336';
            ctx.lineWidth = 2;
            ctx.fill();
            ctx.stroke();
            
            // 绘制内圈
            ctx.beginPath();
            ctx.arc(x, y, 4, 0, 2 * Math.PI);
            ctx.fillStyle = '#f44336';
            ctx.fill();
            
            // 绘制数据值
            ctx.fillStyle = '#f44336';
            ctx.font = 'bold 14px sans-serif';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'bottom';
            ctx.fillText(`${item.time}`, x, y - 12);
          });
        });
    }
  });